package main

import (
	"fmt"
	"encoding/binary"
)

// 校验和计算函数（CHKSUM）
func calculateChecksum(data []byte) []byte {
	var sum int32
	for _, b := range data {
		sum += int32(b)
	}
	checksum := sum % 65536
	checksum = ^checksum + 1
	return []byte{byte(checksum >> 8), byte(checksum & 0xFF)}
}

// 构建获取系统参数命令帧
func buildGetSystemParametersCommand() []byte {
	soi := []byte{0x7E}    // SOI
	ver := []byte{0x21}    // VER
	adr := []byte{0x01}    // ADR
	cid1 := []byte{0x60}   // CID1: 设备类型 - 分散空调
	cid2 := []byte{0x47}   // CID2: 获取系统参数命令
	length := []byte{0x00, 0x00} // LENGTH (LENID=0)
	checksum := calculateChecksum(append(soi, append(ver, append(adr, append(cid1, append(cid2, append(length, ...)))))))
	eoi := []byte{0x0D}    // EOI

	// 拼接完整的命令帧
	commandFrame := append(soi, append(ver, append(adr, append(cid1, append(cid2, append(length, append(checksum, eoi...)...)...)...)
	return commandFrame
}

// 构建获取系统参数响应帧
func buildGetSystemParametersResponse(returnCode byte, params []int16) []byte {
	soi := []byte{0x7E}    // SOI
	ver := []byte{0x21}    // VER
	adr := []byte{0x01}    // ADR
	cid1 := []byte{0x60}   // CID1: 设备类型 - 分散空调
	rtc := []byte{returnCode} // RTN: 返回码
	length := []byte{0x00, 0x30} // LENGTH (LENID=48, 48 bytes data)
	
	// DATA INFO: 将每个参数转换为 2-byte 并拼接
	dataInfo := []byte{}
	for _, param := range params {
		buf := make([]byte, 2)
		binary.BigEndian.PutUint16(buf, uint16(param))
		dataInfo = append(dataInfo, buf...)
	}

	checksum := calculateChecksum(append(soi, append(ver, append(adr, append(cid1, append(rtc, append(length, append(dataInfo, ...)))))))
	eoi := []byte{0x0D}    // EOI

	// 拼接完整的响应帧
	responseFrame := append(soi, append(ver, append(adr, append(cid1, append(rtc, append(length, append(dataInfo, append(checksum, eoi...)...)...)...)
	return responseFrame
}

func main() {
	// 示例：构建获取系统参数命令
	commandFrame := buildGetSystemParametersCommand()
	fmt.Printf("获取系统参数命令帧: %X\n", commandFrame)

	// 示例：构建获取系统参数响应帧，假设返回值为0，参数为24.0℃、60%湿度等
	params := []int16{240, 600, 500, 500, 300, 300, 350, 300, 550, 500, 450, 250}
	responseFrame := buildGetSystemParametersResponse(0x00, params)
	fmt.Printf("获取系统参数响应帧: %X\n", responseFrame)
}
